package cn.com.yang.file;

import java.util.ArrayList;  
import java.util.List;  
import java.util.concurrent.*;  
  
public class MultiThreadedProcessing {  
  
    private static final int TOTAL_DATA = 100000;  
    private static final int DATA_PER_THREAD = 10000;  
    private static final int THREAD_COUNT = TOTAL_DATA / DATA_PER_THREAD;  
  
    public static void main(String[] args) throws InterruptedException, ExecutionException {  
        // 假设你有一个包含10万条数据的列表  
        List<Integer> data = new ArrayList<>(TOTAL_DATA);  
        for (int i = 0; i < TOTAL_DATA; i++) {  
            data.add(i);  
        }  
  
        // 创建一个固定大小的线程池  
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);  
  
        // 提交任务  
        List<Future<?>> futures = new ArrayList<>();  
        for (int i = 0; i < THREAD_COUNT; i++) {  
            int start = i * DATA_PER_THREAD;  
            int end = Math.min((i + 1) * DATA_PER_THREAD, TOTAL_DATA);  
            List<Integer> subData = data.subList(start, end);  
            Future<?> future = executor.submit(new DataProcessor(subData));  
            futures.add(future);  
        }  
  
        // 等待所有任务完成  
        for (Future<?> future : futures) {  
            future.get(); // 这会阻塞，直到任务完成  
        }  
  
        // 关闭线程池  
        executor.shutdown();  
    }  
  
    static class DataProcessor implements Runnable {  
        private final List<Integer> data;  
  
        public DataProcessor(List<Integer> data) {  
            this.data = data;  
        }  
  
        @Override  
        public void run() {  
            // 处理数据的逻辑  
            for (Integer value : data) {  
                // 示例处理逻辑：打印值  
                System.out.println(Thread.currentThread().getName() + " is processing " + value);  
                // 这里可以添加你自己的数据处理逻辑  
            }  
        }  
    }  
}